package org.chen.web.controller.admin;

import org.chen.common.RespUtils;
import org.chen.model.Category;
import org.chen.respmsg.RespEnum;
import org.chen.service.ArticleService;
import org.chen.service.CategoryService;
import org.chen.vo.CategoryInfo;
import org.chen.vo.RespBean;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/admin/category")
public class CategoryController {

    @Autowired
    CategoryService service;

    @Autowired
    ArticleService articleService;

    @GetMapping("/")
    public RespBean<List<CategoryInfo>> getAllCategories(){
        List<Category> list = service.getAllCategories();
        List<CategoryInfo> categoryInfoList=list.stream().map(item->{
            CategoryInfo info=new CategoryInfo();
            BeanUtils.copyProperties(item,info);
            Long count = articleService.getArticleCountByCategory(item.getId());
            info.setArticleCount(count);
            return info;
        }).collect(Collectors.toList());
        return RespUtils.result(categoryInfoList, RespEnum.SUCCESS);
    }

    @PostMapping("/")
    public RespBean<String> addCategory(String name){
        if (service.addCategory(name)==1){
            return RespUtils.result(RespEnum.INSERT_SUCCESS);
        }
        return RespUtils.result(RespEnum.INSERT_FAIL);
    }

    @PutMapping("/")
    public RespBean<String> updateCategory(Integer id,String name){
        if (service.updateCategoryById(id,name)==1){
            return RespUtils.result(RespEnum.UPDATE_SUCCESS);
        }
        return RespUtils.result(RespEnum.UPDATE_FAIL);
    }

    @DeleteMapping("/{id}")
    public RespBean<String> delCategory(@PathVariable("id") Integer id){
        Long count = articleService.getArticleCountByCategory(id);
        if (count >0){
            return RespUtils.fail("该栏目下有文章，不可删除");
        }
        if (service.delCategoryById(id)==1){
            return RespUtils.result(RespEnum.DELETE_SUCCESS);
        }
        return RespUtils.result(RespEnum.DELETE_FAIL);
    }

    //根据RFC标准文档，DELETE请求的body在语义上没有任何意义
    //其实还是可以使用DeleteMapping
    // 请求url就会是：/admin/category/1，2，3，4 这样的url,
    // 但是url是有长度限制的，所以还是用post
    @PostMapping("/deletes")
    public RespBean<String> delCategories(Integer[] ids){
        if (ids==null||ids.length==0){
            return RespUtils.fail("ids不能为空");
        }
        for (int i = 0; i < ids.length; i++) {
            Long count = articleService.getArticleCountByCategory(ids[i]);
            if (count>0){
                return RespUtils.fail("栏目下有文章，不可删除");
            }
        }
        if (service.delCategoryByIds(ids)==ids.length){
            return RespUtils.result(RespEnum.DELETE_SUCCESS);
        }
        return RespUtils.result(RespEnum.DELETE_FAIL);
    }
}
